<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>React入门 - Props与State的使用场景</title>
</head>
<body>
  <ol style="color: red">
    <li>组件props是只读的，保持不变，通常用于组件之间传值(父到子单向传递，即单向数据流)；state维持组件内部状态，可通过setState()来改变</li>
    <li>组件可在内部设置默认props(defaultProps，必须为static), 当外部不传入对应的属性时使用默认值</li>
    <li>组件可在内部设置props的类型以及是否必须(propTypes, 必须为static, isRequired)，以规范组件间传值的合法性</li>
  </ol>
  <div id="container"></div>
  <script src="../../js/react.development.js"></script>
  <script src="../../js/react-dom.development.js"></script>
  <script src="../../js/prop-types.js"></script>
  <script src="../../js/babel.min.js"></script>
  <script type="text/babel">
    // 单组件中使用props和state
    class MyApp extends React.Component {
      static defaultProps = {
        // name: 'Miracle',
        gender: 'Male'
      };

      static propTypes = {
        name: PropTypes.string.isRequired,
        gender: PropTypes.string
      };

      state = {
        age: 32,
        skills: []
      };

      render() {
        const { name, gender } = this.props;
        const { age, skills } = this.state;
        return (
          <div>
            <h2>我是{name}, 性别{gender}</h2>
            <p>今年{age}岁, 正在学习以下技能：</p>
            <ul>
              {
                skills.map((item, index) => (
                  <li key={index}>{item}</li>
                ))
              }
            </ul>
            <button onClick={()=>this.handleUpdate()}>更新个人资料</button>
          </div>
        )
      }

      handleUpdate() {
        const { age, skills } = this.state;
        skills.push('react,redux,router');

        this.setState({
          age: age + 1,
          skills
        });
      }
    }
    ReactDOM.render(<MyApp name="Miracle He"/>, document.getElementById('container'));
  </script>
</body>
</html>
